﻿using System.Collections.Generic;
using System.Linq;
using DynamicChart.Model;
using DynamicChart.Util;
using Microsoft.EntityFrameworkCore;

namespace DynamicChart.Repository;

public class DbTableStructureRepository
{
    private readonly AppDbContext _context;

    public DbTableStructureRepository(AppDbContext context)
    {
        _context = context;
    }
    
    public List<TableStructureModel> GetAll()
    {
        var sql = @"
            SELECT
              c.TABLE_NAME,
              c.COLUMN_NAME,
              c.COLUMN_COMMENT,
              t.TABLE_COMMENT
            FROM
              INFORMATION_SCHEMA.COLUMNS c
              INNER JOIN information_schema.TABLES t ON c.TABLE_NAME = t.TABLE_NAME
              AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
            WHERE
              c.TABLE_SCHEMA = DATABASE()
            ORDER BY
              c.TABLE_NAME,
              c.ORDINAL_POSITION;";

        return _context.TableStructures
            .FromSqlRaw(sql)
            .AsEnumerable() // 在客户端执行后续逻辑（如处理 REMARK）
            .Select(x => new TableStructureModel
            {
                TABLE_NAME = x.TABLE_NAME,
                TABLE_COMMENT = x.TABLE_COMMENT,
                COLUMN_NAME = x.COLUMN_NAME,
                COLUMN_COMMENT = x.COLUMN_COMMENT
                // REMARK 是计算属性，无需赋值
            })
            .ToList();
    }
}